package com.whut.transportation.ui;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.whut.transportation.HomeActivity;
import com.whut.transportation.LoginActivity;
import com.whut.transportation.R;
import com.whut.transportation.network.HttpManager;
import com.whut.transportation.network.HttpRequestVo;
import com.whut.transportation.network.RequestListener;
import com.whut.transportation.network.WebServiceManager;
import com.whut.transportation.network.WebServiceRequestVo;
import com.whut.transportation.overweight.OWHomeActivity;
import com.whut.transportation.utils.AppManager;
import com.whut.transportation.utils.BaseApplication;


/**
 * ============================================================
 * 
 * 应用程序Activity的基类 管理 Activity 主要从服务器拿数据 
 * 
 * 修订历史 ：
 * 
 * ============================================================
 **/

public abstract class BaseActivity extends Activity implements OnClickListener {
	protected int activityCase;
	protected ProgressDialog progressDialog;
	protected Dialog dialog = null;
	protected TextView textShopCarNum;
	protected Context mContext;
	protected BaseApplication app;
	public HttpManager httpManager;
	public WebServiceManager webManager;
	private final static int SHOW_NETERROR_DIALOG = 1;
	private static final int SHOW_SETNET_DIALOG = 0;
	protected ImageView titleBarBackBTN = null;
	protected TextView titleBarMiddleTV = null;
	protected ImageView titleBarHomeBTN = null;
	protected TextView titleBarFunBTN = null;
	protected View loadingView;
	protected ProgressBar loadingPb;
	protected TextView loadingTv;
	protected Handler mHandler = null;
	SharedPreferences preferences;

	/**
	 * Android生命周期回调方法-创建
	 */
	@Override
	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		// 设置没有标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mContext = this;
		app = (BaseApplication) getApplication();
		AppManager.getAppManager().addActivity(this);
		preferences = getSharedPreferences("userId", Context.MODE_PRIVATE);
		initView();
	}
	/**
	 * 通过类名启动Activity
	 * 
	 * @param pClass
	 */
	protected void openActivity(Class<?> pClass) {
		openActivity(pClass, null);
	}
	/**
	 * 通过类名启动Activity，并且含有Bundle数据
	 * 
	 * @param pClass
	 * @param pBundle
	 */
	protected void openActivity(Class<?> pClass, Bundle pBundle) {
		Intent intent = new Intent(this, pClass);
		if (pBundle != null) {
			intent.putExtras(pBundle);
		}
		startActivity(intent);
	}
	/**
	 * Android生命周期回调方法-销毁
	 */
	@Override
	protected void onDestroy() {
		AppManager.getAppManager().finishActivity(this);
		super.onDestroy();

	}

	@Override
	protected void onResume() {

		super.onResume();
		overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	/**
	 * 设置titlebar
	 */
	protected void setTitleBarView(boolean isShowBack, String middleStr,
			int funResource, boolean isShowHome) {
		View titleBarView = this.findViewById(R.id.title_bar);
		titleBarBackBTN = (ImageView) titleBarView
				.findViewById(R.id.title_bar_back_btn);
		titleBarMiddleTV = (TextView) titleBarView
				.findViewById(R.id.title_bar_middle_tv);
		titleBarFunBTN = (TextView) titleBarView
				.findViewById(R.id.title_bar_fun_btn);
		titleBarHomeBTN = (ImageView) titleBarView
				.findViewById(R.id.title_bar_home_btn);
		if (isShowBack) {
			titleBarBackBTN.setVisibility(View.VISIBLE);
			titleBarBackBTN.setOnClickListener(this);
		}
		titleBarMiddleTV.setText(middleStr);
		if (funResource != -1) {
			titleBarFunBTN.setVisibility(View.VISIBLE);
			titleBarFunBTN.setOnClickListener(this);
		}
		if (isShowHome) {
			titleBarHomeBTN.setVisibility(View.VISIBLE);
			titleBarHomeBTN.setOnClickListener(this);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_bar_back_btn:
			this.finish();
			break;
		case R.id.title_bar_home_btn:
			//((HomeActivity)(this.getParent())).closeIndex(getTabIndex());
			if(preferences.getInt("flag", 0)==2){
				Intent intent = new Intent(this,HomeActivity.class);
				startActivity(intent);
				finish();
			} else if(preferences.getInt("flag", 0)==3){
				Intent chaozhongyuan = new Intent(this, OWHomeActivity.class);
				startActivity(chaozhongyuan);
				finish();
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		loadViewLayout();
		findViewById();
		afterFindViewId();
		processLogic();
		setListener();
	}

	/**
	 * 类功能描述：处理网络数据的显示</br>
	 * 
	 * @author 
	 * @version 1.0 </p> 修改时间：</br> 修改备注：</br>
	 */

	class BaseHandler extends Handler {
		private Context context;
		private DataCallback callBack;

		public BaseHandler(Context context, DataCallback callBack
				) {
			this.context = context;
			this.callBack = callBack;
		}

		public void handleMessage(Message msg) {
			if (msg.what == RequestListener.EVENT_GET_DATA_SUCCESS) {
				if (msg.obj == null) {
					callBack.onFailed();

				} else {
					// 后台处理数据
					callBack.processData(msg.obj, true);
				}
			} else if (msg.what == RequestListener.EVENT_NOT_NETWORD) {
				showNetFailedDialog();
				// CommonUtil.showInfoDialog(context,
				// getString(R.string.net_error));
			} else if (msg.what == RequestListener.EVENT_NETWORD_EEEOR) {
				callBack.onFailed();
			} else if (msg.what == RequestListener.EVENT_GET_DATA_EEEOR) {
				callBack.onFailed();

			} else if (msg.what == RequestListener.EVENT_CLOSE_SOCKET) {
				
			}
			callBack.onFinish();
		}

	}

	public void showNetFailedDialog() {
		showDialog(SHOW_SETNET_DIALOG);

	}

	public void showNetErrorDialog() {
		showDialog(SHOW_NETERROR_DIALOG);

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case SHOW_NETERROR_DIALOG:
			if (!isFinishing()) {
				dialog = new AlertDialog.Builder(this)
						.setTitle("提示")
						.setMessage("网络不稳定！请重试")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										getDataAgain();

									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										dialog.cancel();
									}
								}).create();
			}
			break;
		case SHOW_SETNET_DIALOG:
			if (!isFinishing()) {
				dialog = new AlertDialog.Builder(this)
						.setTitle("提示")
						.setMessage("没用网络连接，请设置网络！")
						.setPositiveButton("设置网络",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										startActivityForResult(
												new Intent(
														android.provider.Settings.ACTION_WIRELESS_SETTINGS),
												0);
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										dialog.cancel();
										// closeApp();
									}
								}).create();
			}
			break;

		default:
			return super.onCreateDialog(id);
		}
		return dialog;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 0:
			getDataAgain();
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public boolean checkApp(String packageName) {
		if (packageName == null || "".equals(packageName))
			return false;
		try {
			ApplicationInfo info = getPackageManager().getApplicationInfo(
					packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
			return true;
		} catch (NameNotFoundException e) {
			return false;
		}
	}

	protected void closeApp() {
		AppManager.getAppManager().AppExit(mContext);
	}

	/**
	 * 类功能描述：回调接口，用于后台处理数据
	 * 
	 * @author
	 * @version 1.0
	 * @param <T>
	 *            </p> 修改时间：</br> 修改备注：</br>
	 */
	public abstract interface DataCallback<T> {
		public abstract void onStart();
		public abstract void onFailed();

		public abstract void processData(T paramObject, boolean paramBoolean);

		public abstract void onFinish();
	}

	/**
	 * 从服务器上获取数据，并回调处理
	 * 
	 * @param reqVo
	 * @param callBack
	 */
	protected void getDataFromServer(int requestType, HttpRequestVo reqVo,
			DataCallback callBack) {
		final BaseHandler handler = new BaseHandler(this, callBack);
		httpManager = new HttpManager(mContext, new RequestListener() {

			@Override
			public void action(int actionCode, Object object) {

				Message msg = Message.obtain();
				switch (actionCode) {
				case RequestListener.EVENT_NOT_NETWORD:
					msg.what = RequestListener.EVENT_NOT_NETWORD;
					break;

				case RequestListener.EVENT_NETWORD_EEEOR:
					msg.what = RequestListener.EVENT_NETWORD_EEEOR;
					break;
				case RequestListener.EVENT_CLOSE_SOCKET:
					msg.what = RequestListener.EVENT_CLOSE_SOCKET;
					break;

				case RequestListener.EVENT_GET_DATA_EEEOR:
					msg.what = RequestListener.EVENT_GET_DATA_EEEOR;
					msg.obj = null;
					break;
				case RequestListener.EVENT_GET_DATA_SUCCESS:
					msg.obj = object;
					msg.what = RequestListener.EVENT_GET_DATA_SUCCESS;
					break;
				default:
					break;
				}
				handler.sendMessage(msg);
			}
		}, reqVo);
		callBack.onStart();
		if (requestType == HttpManager.GET_MOTHOD) {
			httpManager.getRequeest();
		} else if (requestType == HttpManager.POST_MOTHOD) {
			httpManager.postRequest();
		}
	}

	/**
	 * 从WebService上获取数据，并回调处理
	 * @param reqVo
	 * @param callBack
	 */
	protected void getDataFromWebService(WebServiceRequestVo reqVo,
			DataCallback callBack) {
		final BaseHandler handler = new BaseHandler(this, callBack);
		webManager = new WebServiceManager(mContext, new RequestListener() {

			@Override
			public void action(int actionCode, Object object) {

				Message msg = new Message();
				switch (actionCode) {
				case RequestListener.EVENT_NOT_NETWORD:
					msg.what = RequestListener.EVENT_NOT_NETWORD;
					break;

				case RequestListener.EVENT_NETWORD_EEEOR:
					msg.what = RequestListener.EVENT_NETWORD_EEEOR;
					break;
				case RequestListener.EVENT_CLOSE_SOCKET:
					msg.what = RequestListener.EVENT_CLOSE_SOCKET;
					break;

				case RequestListener.EVENT_GET_DATA_EEEOR:
					msg.what = RequestListener.EVENT_GET_DATA_EEEOR;
					msg.obj = null;
					break;
				case RequestListener.EVENT_GET_DATA_SUCCESS:
					msg.obj = object;
					msg.what = RequestListener.EVENT_GET_DATA_SUCCESS;
					break;
				default:
					break;
				}
				handler.sendMessage(msg);

			}
		}, reqVo);
		callBack.onStart();
		webManager.request();

	}
	// /**
	// * 显示正在加载页面
	// */
	// protected void showLoadingView() {
	// if (loadingView == null) {
	// loadingView = findViewById(R.id.loading_view);
	// loadingPb = (ProgressBar) loadingView
	// .findViewById(R.id.progressBar_loading);
	// loadingTv = (TextView) loadingView.findViewById(R.id.tv_loading);
	// }
	// loadingView.setVisibility(View.VISIBLE);
	// loadingPb.setVisibility(View.VISIBLE);
	// loadingTv.setText("正在获取数据，请稍后……");
	// loadingView.setOnClickListener(null);
	// }

	// /**
	// * 去除加载页面
	// */
	// protected void closeLoadingView() {
	// if (loadingView != null) {
	// loadingView.setVisibility(View.INVISIBLE);
	// loadingView = null;
	// }
	//
	// }

	/**
	 * 显示正在加载提示框
	 */
	protected void showProgressDialog(String message) {
		if ((!isFinishing()) && (this.progressDialog == null)) {
			this.progressDialog = new ProgressDialog(this);
		}
		progressDialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == event.KEYCODE_BACK) {
					if (httpManager != null) {
						httpManager.cancelHttpRequest();
					}
				}
				return false;
			}
		});
//		progressDialog.setCancelable(false);
		// this.progressDialog.setTitle(getString(R.string.loadTitle));
		this.progressDialog.setMessage(message);
		this.progressDialog.show();
	}

	/**
	 * 关闭提示框
	 */
	protected void closeProgressDialog() {
		if (this.progressDialog != null)
			this.progressDialog.dismiss();
	}

	/**
	 * find控件
	 */
	protected abstract void findViewById();
	protected abstract void afterFindViewId();
	/**
	 * 加载布局
	 */
	protected abstract void loadViewLayout();

	/**
	 * 后台获取数据
	 */
	protected abstract void processLogic();

	/**
	 * 设置监听
	 */
	protected abstract void setListener();

	/**
	 * 重新获取数据
	 */
	protected abstract void getDataAgain();

	/**
	 * 如果是tab的子activity，返回编号
	 */
	protected int getTabIndex() {
		return 0;
	}
}
